<template>
  <ElTree
    ref="tree"
    :default-expanded-keys="defaultExpandedKeys"
    :default-checked-keys="defaultCheckedKeys"
    :expand-on-click-node="false"
    :load="handLoadNode"
    :check-strictly="checkStrictly"
    :data="treeData"
    :props="defaultProps"
    :show-checkbox="isMultiple"
    highlight-current
    node-key="id"
    @node-click="handleNodeClick">
    <template #default="{ node }">
      <span> <i class="el-icon-office-building"></i> {{ node.label }}</span>
    </template>
  </ElTree>
</template>

<script>
  import { fetchTree } from '@/api/admin/dept'

  export default {
    name: 'DepartmentTree',
    props: {
      isMultiple: {
        type: Boolean,
        default: false
      },
      checkStrictly: Boolean,
      preSelectedUsers: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        defaultExpandedKeys: [],
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'name',
          isLeaf: function (data) {
            return !data.hasChildren
          }
        }
      }
    },
    computed: {
      defaultCheckedKeys() {
        return this.preSelectedUsers
      }
    },
    created() {
      this.handLoadNode()
    },
    methods: {
      async handLoadNode(node, resolve) {
        const res = await fetchTree()
        this.treeData = res.data.data
      },
      getCheckedNodes() {
        if (this.isMultiple) {
          return this.$refs.tree.getCheckedNodes()
        } else {
          return this.$refs.tree.getCurrentNode()
        }
      },
      handleNodeClick(node) {
        if (node.showType === undefined) {
          this.$emit('node-click', node)
        }
      }
    }
  }
</script>
